package com.summer.safe.utils;

import com.summer.safe.entity.GenScheme;
import com.summer.safe.entity.GenTable;
import com.summer.safe.entity.GenTableColumn;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 代码生成工具类
 */
public class GenUtils {




    /**
     * 获得代码生成的配置信息
     * @param table
     * @param scheme
     * @param tableColumnList
     * @return
     */
    public static GenerateConfig config(GenTable table, GenScheme scheme, List<GenTableColumn> tableColumnList) {
        GenerateConfig config = new GenerateConfig();
        config.setGen(table);
        config.setScheme(scheme);

        Set<String> set = new HashSet<>();
        tableColumnList.forEach(tableColumn -> {
            if (StringUtils.indexOf(tableColumn.getJavaType(), ".") != -1) {
                String simpleJavaType = getSimpleJavaType(tableColumn.getJavaType());
                String fil = ToolUtil.firstLetterToLower(ToolUtil.humpStr(tableColumn.getName()));
                if (ToolUtil.getIsNotBaseField(fil)) {
                    set.add(tableColumn.getJavaType());
                }
                if(tableColumn.getJavaType().equals("java.util.Date")){
                    set.add("com.fasterxml.jackson.annotation.JsonFormat");
                }
                tableColumn.setJavaType(simpleJavaType);
            }
            tableColumn.setJavaField(getSimpleJavaField(tableColumn.getJavaField()));
        });

        config.setImportNames(set);
        config.setTableColumnList(tableColumnList);

        config.setProjectPath(Global.getPath());

        return config;
    }

    /**
     * 获取简写Java类型
     *
     * @return
     */
    public static String getSimpleJavaType(String javaType) {
        return StringUtils.indexOf(javaType, ".") != -1
                ? StringUtils.substringAfterLast(javaType, ".")
                : javaType;
    }

    /**
     * 获取简写Java字段
     *
     * @return
     */
    public static String getSimpleJavaField(String javaField) {
        return StringUtils.substringBefore(javaField, ".");
    }
}
